import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {Form, Input, Select, DatePicker, Button, Row, Col} from 'antd'

import styles from './index.less'

import {isPhone} from 'kuan-utils/src/validate'

const {RangePicker} = DatePicker
const {TextArea} = Input
const FormItem = Form.Item
const {Option} = Select

const formItemLayout = {}

@Form.create()
class MyForm extends Component {
  static propTypes = {
    data: PropTypes.array.isRequired,
    title: PropTypes.string,
    onOk: PropTypes.func,
    onCancel: PropTypes.func,
  }

  static defaultProps = {
    title: '编辑',
  }

  validatePhone = (rule, value, callback) => {
    if (!isPhone(value)) {
      return callback('请正确输入手机号')
    }
    callback()
  }

  submit = (e) => {
    e.preventDefault()
    const {form, onOk} = this.props
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        onOk(values)
      }
    })
  }

  // options => {} || []
  renderSelect = (options, message) => {
    if (Array.isArray(options)) {
      return (
        <Select placeholder={message}>
          {options.map(option => (
            <Option
              key={option.value || option.id}
              value={(option.value ? option.value.toString : '') || option.id.toString()}
            >{option.name}
            </Option>)
          )}
        </Select>
      )
    }
    return (
      <Select placeholder={message}>
        {Object.entries(options).map(([key, name]) => <Option key={key} value={key}>{name}</Option>
        )}
      </Select>
    )
  }

  renderItem = (type, options, message, placeholder) => {
    const components = {
      Select: this.renderSelect(options, message),
      DatePicker: <DatePicker placeholder={placeholder || message} />,
      RangePicker: <RangePicker />,
      TextArea: <TextArea placeholder={placeholder || message} />
    }
    return components[type] || <Input placeholder={message} />
  }

  renderFormItem = ({label, key, rules, type, options = [], initialValue, component, placeholder, disabled}) => {
    const {form} = this.props
    const {getFieldDecorator} = form
    const message = `请输入${label}`
    rules = rules || [{required: true, message}]
    if (type === 'phone') {
      rules.push({
        validator: this.validatePhone
      })
    }
    const config = {rules}
    if (initialValue) config.initialValue = initialValue
    const innerItem = () => {
      if (component) return component
      return !type ? <Input disabled={disabled} placeholder={placeholder || message} /> :
        this.renderItem(type, options, message, placeholder, disabled)
    }

    return (
      <Col key={key} sm={12} md={6}>
        <FormItem {...formItemLayout} label={label}>
          {getFieldDecorator(key, config)(
            innerItem()
          )}
        </FormItem>
      </Col>
    )
  }

  render() {
    const {data, onOk, onCancel, layout = 'inline'} = this.props
    return (
      <Form layout={layout} onSubmit={this.handleSubmit}>
        <Row gutter={24}>
          {data.map(item => this.renderFormItem(item))}
        </Row>

        {(onOk || onCancel) &&
          <div className={styles.action}>
            <Button onClick={this.submit} type='primary'>确定</Button>
            <Button onClick={onCancel}>取消</Button>
          </div>
        }
      </Form>
    )
  }
}

export default MyForm
